package mapevents;

import enumm.GROUND;
import gameengine.map.Field;
import gameengine.map.Map;
import gameengine.map.Path;
import gameengine.map.unit.Unit;

public final class MapSelection extends AbstractMapEvent {

    private final transient int xStart;
    private final transient int yStart;
    private final transient Unit unit;

    public MapSelection(final int xCoordinate, final int yCoordinate, final Unit selectedUnit) {
        super();
        xStart = xCoordinate;
        yStart = yCoordinate;
        this.unit = selectedUnit;
    }

    @Override
    public MAPEVENTTYPE getType() {
        return MAPEVENTTYPE.SELECT;
    }

    @Override
    public int getXStart() {
        return xStart;
    }

    @Override
    public int getYStart() {
        return yStart;
    }

    @Override
    public int getXTarget() {
        return 0;
    }

    @Override
    public int getYTarget() {
        return 0;
    }

    @Override
    public Unit getUnit() {
        return unit;
    }

    @Override
    public Unit getAttacker() {
        return null;
    }

    @Override
    public AbstractMapEvent newMapEvent(final int xClick, final int yClick, final boolean leftClick, final Map map, final int party) {
        final Field field = map.getField(xClick, yClick);
        final Unit tmpUnit = field.getUnit();

        AbstractMapEvent event;

        if (tmpUnit == null) {
            final Path path = new Path(xStart, yStart, map);
            if (path.getNode(xClick, yClick) == null) {
                if (field.getGround() == GROUND.BUILDING) {
                    event = new BuildingEvent(xClick, yClick);
                } else {
                    event = new MapDeSelection(xClick, yClick, tmpUnit);
                }
            } else {
                event = new MapMoveEvent(this, new MapSelection(xClick, yClick, tmpUnit));
            }
        } else {
            if (tmpUnit.getParty() == party) {
                if (leftClick) {
                    if (xClick == xStart && yClick == yStart) {
                        event = new MapDeSelection(xClick, yClick, tmpUnit);
                    } else {
                        event = new MapSelection(xClick, yClick, tmpUnit);
                    }
                } else {
                    event = new MapFireRangeSelection(xClick, yClick, tmpUnit);
                }
            } else {
                event = new MapDeSelection(xClick, yClick, tmpUnit);
            }
        }
        return event;
    }
}
